clear
clear all
cap log close

log using "log-files/2_Figure_F1.smcl", replace smcl

timer on 2

*------------*
* Figure F.1 *
*------------*
	* Creating a temporary data set with a random number for each
	* polling booth, for every different sorting
	use "data/outputs/computo_verificadortrepdate_nomissings.dta", clear
	keep NumMesa

	expand $rdreps
	bys NumMesa: gen sorting = _n

	gen random_draw = runiform()

	compress
	saveold "data/outputs/randomdraws_rd.dta", replace

	* Figure F.1a
	*------------
		matrix R2 = J($rdreps, 2, .)

		forvalues k = 1 / $rdreps {
			use if sorting == `k' using "data/outputs/randomdraws_rd.dta", clear
			drop sorting
			compress
			saveold "data/outputs/temp.dta", replace

			use "data/outputs/computo_verificadortrepdate_nomissings.dta", clear
			keep Pais-trep_missing_date_verificador

			quietly merge 1:1 NumMesa using "data/outputs/temp.dta"
			drop _merge

			* Measures that DO USE Blancos and Nulos (sorted)
			gen total_so = CC + FPV + MTS + UCS + MAS + F + PDC + MNR + PANBOL + ///
				Blancos + Nulos
			*---*
			gen mshare_so = MAS / total_so
			gen cshare_so = CC / total_so
			sort trep_date_verificador random_draw
			gen cumsumtotal_so = sum(total_so)
			*---*
			egen maxcumsumtotal_so = max(cumsumtotal_so)
			gen pcs_so = cumsumtotal_so / maxcumsumtotal_so
			drop cumsumtotal_so maxcumsumtotal_so

			* Recinto ID
			egen reci_id = group(Pais Dep Prov Muni Loc Reci)
			tostring reci_id, replace
			replace reci_id=reci_id+"-1" if Dep=="La Paz" & Prov=="Murillo" & ///
				Muni=="Nuestra Señora de La Paz" & Reci=="Unidad Educativa Privada La Paz" ///
				& NumMesa>=22383 & NumMesa<=22386
			replace reci_id=reci_id+"-2" if Dep=="La Paz" & Prov=="Murillo" & ///
				Muni=="Nuestra Señora de La Paz" & Reci=="Unidad Educativa Privada La Paz" ///
				& NumMesa>22386
			egen preci_cluster = group(reci_id)

			* Rdrobust
			quietly rdrobust mshare pcs, c(0.95) vce(cluster preci_cluster)
			matrix R2[`k', 1] = e(tau_cl)
			matrix R2[`k', 2] = 2 * normal(-abs(e(tau_bc) / e(se_tau_rb)))
		}

		erase "data/outputs/temp.dta"

		clear
		svmat R2

		sum R21, detail
		local median = r(p50)
		local median_lab = `median' + 0.005 / 9

		twoway (scatter R21 R22, msize(vsmall) mcolor(midblue)), ///
			xtitle("Robust p-value") ytitle("RD Conventional Estimator") ///
			ylabel(, angle(0)) ///
			yline(`median', lcolor(black) lpattern(dash)) ///
			graphregion(color(white)) xlabel(0(0.1)1) ///
			xline(0.01 0.05 0.1, lcolor(black) lpattern(dash)) ///
			text(`median_lab' 0.95 "Median")
		graph export "outputs/generated/Figure_F1a.pdf", replace

	* Figure F.1b
	*------------
		matrix R0 = J($rdreps,2, .)

		forvalues k = 1 / $rdreps {
			use if sorting == `k' using "data/outputs/randomdraws_rd.dta", clear
			drop sorting
			compress
			saveold "data/outputs/temp.dta", replace

			use "data/outputs/computo_verificadortrepdate_nomissings.dta", clear
			keep Pais-trep_missing_date_verificador
			
			quietly merge 1:1 NumMesa using "data/outputs/temp.dta"
			drop _merge

			* Measures that DO USE Blancos and Nulos (sorted)
			gen total_so = CC + FPV + MTS + UCS + MAS + F + PDC + MNR + PANBOL + ///
				Blancos + Nulos
			*---*
			gen mshare_so = MAS / total_so
			gen cshare_so = CC / total_so
			sort trep_date_verificador random_draw
			gen cumsumtotal_so = sum(total_so)
			*---*
			egen maxcumsumtotal_so = max(cumsumtotal_so)
			gen pcs_so = cumsumtotal_so / maxcumsumtotal_so
			drop cumsumtotal_so maxcumsumtotal_so

			* Defining the cutoff
			quietly sum pcs if trep_date_verificador >= tc(20oct2019 19:40:57)
			local cutoff = r(min)

			* Recinto ID
			egen reci_id = group(Pais Dep Prov Muni Loc Reci)
			tostring reci_id, replace
			replace reci_id=reci_id+"-1" if Dep=="La Paz" & Prov=="Murillo" & ///
				Muni=="Nuestra Señora de La Paz" & Reci=="Unidad Educativa Privada La Paz" ///
				& NumMesa>=22383 & NumMesa<=22386
			replace reci_id=reci_id+"-2" if Dep=="La Paz" & Prov=="Murillo" & ///
				Muni=="Nuestra Señora de La Paz" & Reci=="Unidad Educativa Privada La Paz" ///
				& NumMesa>22386
			egen preci_cluster = group(reci_id)

			* Rdrobust
			quietly rdrobust mshare pcs, c(`cutoff') vce(cluster preci_cluster)
			matrix R0[`k', 1] = e(tau_cl)
			matrix R0[`k', 2] = 2 * normal(-abs(e(tau_bc) / e(se_tau_rb)))
		}

		erase "data/outputs/temp.dta"

		clear
		svmat R0

		sum R01, detail
		local median = r(p50)
		local median_lab = `median' + 0.00002

		twoway (scatter R01 R02, msize(vsmall) mcolor(midblue)), ///
			xtitle("Robust p-value") ytitle("RD Conventional Estimator") ///
			ylabel(, angle(0)) ///
			yline(`median', lcolor(black) lpattern(dash)) ///
			graphregion(color(white)) xlabel(0(0.1)1) ///
			xline(0.01 0.05 0.1, lcolor(black) lpattern(dash)) ///
			text(`median_lab' 0.95 "Median")
		graph export "outputs/generated/Figure_F1b.pdf", replace

		* Exporting the data to produce Table D1 in the do-file for tables
		clear
		svmat R0
		svmat R2
		saveold "data/outputs/RD_sortings.dta", replace

		* Finding the draw associated to the mean RD estimate for each case
		keep R01 R21
		gen sorting = _n

		foreach k of numlist 0 2 {
			sum R`k'1, detail
			gen median = r(p50)
			gen dif = abs(R`k'1 - median)
			sort dif
			replace R`k'1 = . if _n > 1
			drop median dif
		}

		egen missings = rownonmiss(R01 R21)
		keep if missings != 0
		gen row = 1 if R21 != .
		replace row = 2 if R01 != .
		keep row sorting
		sort row
		saveold "data/outputs/RD_sortings_mediandraw.dta", replace

		* Making the data set with all of the 1,000 sortings smaller
		levelsof sorting, local(sortings)
		use "data/outputs/randomdraws_rd.dta", clear

		gen keep_obs = 0
		foreach x of local sortings {
			replace keep_obs = 1 if sorting == `x'
		}
		keep if keep_obs == 1
		drop keep_obs

		compress
		saveold "data/outputs/randomdraws_rd.dta", replace

*------------------------------------------------------------------------------*
timer off 2
timer list 2

log close
clear all
